package com.rainbow.service.impl

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.rainbow.constant.RoleConstant
import com.rainbow.entity.User
import com.rainbow.mapper.UserMapper
import com.rainbow.service.UserService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service

@Service
class UserServiceImpl : ServiceImpl<UserMapper, User>(), UserService {

    override fun insert(user: User): Boolean {
        val flag: Boolean
        val username = user.username!!
        if (exist(username)) {
            flag = false
        } else {
            encryptPassword(user)
            user.roles = RoleConstant.ROLE_USER
            save(user)
            flag = true
        }

        return flag
    }

    override fun getByUsername(username: String): User? {
        return getOne(QueryWrapper<User>().eq("username", username))
    }


    /**
     * 判断用户是否存在
     */
    fun exist(username: String): Boolean {
        val user = getByUsername(username)
        return (user != null)
    }

    /**
     * 加密密码
     */
    private fun encryptPassword(user: User) {
        var password = user.password
        password = BCryptPasswordEncoder().encode(password)
        user.password = password
    }

}